package com.ysd.lis.service.bac.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.ysd.common.Result;
import com.ysd.lis.entity.PubReport;
import com.ysd.lis.entity.SysInterface;
import com.ysd.lis.entity.SysUser;
import com.ysd.lis.entity.bac.BacImageResult;
import com.ysd.lis.entity.bac.BacObserResult;
import com.ysd.lis.entity.bac.BacPublisSecReport;
import com.ysd.lis.entity.bac.BacStainingResult;
import com.ysd.lis.entity.lab.LabMaininfo;
import com.ysd.lis.entity.lab.LabRptmain;
import com.ysd.lis.mapper.bac.BacImageResultMapper;
import com.ysd.lis.mapper.bac.BacPublisSecReportMapper;
import com.ysd.lis.mapper.bac.BacStainingResultMapper;
import com.ysd.lis.mapper.lab.LabMaininfoMapper;
import com.ysd.lis.mapper.pub.PubReportMapper;
import com.ysd.lis.mapper.sys.SysInterfaceMapper;
import com.ysd.lis.request.BacGenerateReportRequestParam;
import com.ysd.lis.request.CommonPageDto;
import com.ysd.lis.request.SysParamFieldValueDto;
import com.ysd.lis.request.SysParamParam;
import com.ysd.lis.service.SysBasDictDetailService;
import com.ysd.lis.service.SysParamValueService;
import com.ysd.lis.service.bac.BacObserResultService;
import com.ysd.lis.service.bac.BacPublisSecReportService;
import com.ysd.lis.service.lab.LabRptmainService;
import com.ysd.util.RedisUserManager;
import com.ysd.util.ToolsUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 52771
 * @description 针对表【BAC_PUBLIS_SEC_REPORT】的数据库操作Service实现
 * @createDate 2024-08-14 11:29:36
 */
@Service
public class BacPublisSecReportServiceImpl extends ServiceImpl<BacPublisSecReportMapper, BacPublisSecReport> implements BacPublisSecReportService {

    private static final Logger logger = LoggerFactory.getLogger(BacPublisSecReportServiceImpl.class);


    @Autowired
    BacStainingResultMapper bacStainingResultMapper;
    @Autowired
    BacPublisSecReportMapper bacPublisSecReportMapper;
    @Autowired
    LabRptmainService labRptmainService;
    @Autowired
    SysInterfaceMapper sysInterfaceMapper;
    @Autowired
    LabMaininfoMapper labMaininfoMapper;
    @Autowired
    BacObserResultService bacObserResultService;
    @Autowired
    SysParamValueService sysParamValueService;
    @Autowired
    SysBasDictDetailService basDictDetailService;
    @Autowired
    BacImageResultMapper bacImageResultMapper;
    @Autowired
    PubReportMapper pubReportMapper;

    @Override
    public Result batchCancelSecReport(List<BacPublisSecReport> bacPublisSecReports) {
        if (CollectionUtils.isNotEmpty(bacPublisSecReports)) {
            LambdaQueryWrapper<BacPublisSecReport> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            Timestamp timestamp = new Timestamp(bacPublisSecReports.get(0).getSampleda().getTime());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String formattedDate = sdf.format(timestamp);
            Timestamp startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
            Timestamp endTime = Timestamp.valueOf(formattedDate + " 23:59:59");
            lambdaQueryWrapper.ge(BacPublisSecReport::getSampleda, startTime);
            lambdaQueryWrapper.le(BacPublisSecReport::getSampleda, endTime);
            lambdaQueryWrapper.eq(BacPublisSecReport::getRptGroup, bacPublisSecReports.get(0).getRptGroup());
            lambdaQueryWrapper.eq(BacPublisSecReport::getSampleNo, bacPublisSecReports.get(0).getSampleNo());
            lambdaQueryWrapper.eq(BacPublisSecReport::getTestFlowNo, bacPublisSecReports.get(0).getTestFlowNo());
            lambdaQueryWrapper.eq(BacPublisSecReport::getTestNodeNo, bacPublisSecReports.get(0).getTestNodeNo());
            String strainNo = bacPublisSecReports.get(0).getStrainNo();
            if (ToolsUtils.isNotEmpty(strainNo)) {
                lambdaQueryWrapper.eq(BacPublisSecReport::getStrainNo, bacPublisSecReports.get(0).getStrainNo());
            } else {
                lambdaQueryWrapper.isNull(BacPublisSecReport::getStrainNo);
            }
            boolean remove = this.remove(lambdaQueryWrapper);
            //修改染色结果的状态
            for (BacPublisSecReport bacPublisSecReport : bacPublisSecReports) {
                BacStainingResult bacStainingResult = new BacStainingResult();
                bacStainingResult.setIsPushSecReport(0);
                bacStainingResult.setId(bacPublisSecReport.getStainingResulId());
                bacStainingResultMapper.updateById(bacStainingResult);
            }
            if (remove) {
                //把his的染色报告删除
                SysUser sysUser = RedisUserManager.getUser();
                LambdaQueryWrapper<SysInterface> wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(SysInterface::getDelFlag, 0);
                wrapper.eq(SysInterface::getIsEnable, 1);
                wrapper.eq(SysInterface::getOrgId, sysUser.getOrgId());
                List<SysInterface> sysInterfaces = sysInterfaceMapper.selectList(wrapper);
                List<String> collect = sysInterfaces.stream().filter(o -> Objects.nonNull(o) && StringUtils.isNotBlank(o.getInterfaceUrl())).map(SysInterface::getInterfaceUrl).distinct().collect(Collectors.toList());
                //标本消申
                if (CollectionUtils.isNotEmpty(collect)) {
                    LambdaQueryWrapper<LabMaininfo> lambdaQueryWrapper111 = new LambdaQueryWrapper<>();
                    lambdaQueryWrapper111
                            .eq(LabMaininfo::getRptGroup, bacPublisSecReports.get(0).getRptGroup())
                            .eq(LabMaininfo::getSampleNo, bacPublisSecReports.get(0).getSampleNo())
                            .eq(LabMaininfo::getSampleda, bacPublisSecReports.get(0).getSampleda())
                            .eq(LabMaininfo::getDelFlag, 0);
                    LabMaininfo labMaininfo = labMaininfoMapper.selectOne(lambdaQueryWrapper111);
                    //消审走报告发布传delete
                    for (String webUrl : collect) {
                        Map releaseReportMap1 = new HashMap();
                        String releaseReport1 = webUrl + "/public/releaseWswReport";
                        releaseReportMap1.put("orgId", sysUser.getOrgId());
                        releaseReportMap1.put("mainInfoId", labMaininfo.getId());
                        releaseReportMap1.put("deleteFlag", "1");
                        String release = HttpUtil.createPost(releaseReport1).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(releaseReportMap1)).contentType("application/json").execute().body();
                        logger.info("消审报告返回值:\n" + release);
                    }
                }
            }
        }
        return Result.succ(1, "成功", "");
    }

    //原代码再controller里,迁移到service层
    @Override
    public Result batchEditPublisSecReport(List<BacPublisSecReport> bacPublisSecReports) throws JsonProcessingException {
        List<BacPublisSecReport> reports = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(bacPublisSecReports)) {
            LambdaQueryWrapper<BacPublisSecReport> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            Timestamp timestamp = new Timestamp(bacPublisSecReports.get(0).getSampleda().getTime());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String formattedDate = sdf.format(timestamp);
            Timestamp startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
            Timestamp endTime = Timestamp.valueOf(formattedDate + " 23:59:59");
            lambdaQueryWrapper.ge(BacPublisSecReport::getSampleda, startTime);
            lambdaQueryWrapper.le(BacPublisSecReport::getSampleda, endTime);
            lambdaQueryWrapper.eq(BacPublisSecReport::getRptGroup, bacPublisSecReports.get(0).getRptGroup());
            lambdaQueryWrapper.eq(BacPublisSecReport::getSampleNo, bacPublisSecReports.get(0).getSampleNo());
            lambdaQueryWrapper.eq(BacPublisSecReport::getTestFlowNo, bacPublisSecReports.get(0).getTestFlowNo());
            lambdaQueryWrapper.eq(BacPublisSecReport::getTestNodeNo, bacPublisSecReports.get(0).getTestNodeNo());
            String strainNo = bacPublisSecReports.get(0).getStrainNo();
            if (ToolsUtils.isNotEmpty(strainNo)) {
                lambdaQueryWrapper.eq(BacPublisSecReport::getStrainNo, bacPublisSecReports.get(0).getStrainNo());
            } else {
                lambdaQueryWrapper.isNull(BacPublisSecReport::getStrainNo);
            }
            reports = this.list(lambdaQueryWrapper);
            this.remove(lambdaQueryWrapper);
        }
        boolean b = this.saveBatch(bacPublisSecReports);

        String testNodeNo = bacPublisSecReports.get(0).getTestNodeNo();
        /*山亭(培养审核发送报告)*/
        SysParamParam jdfbg = new SysParamParam();
        jdfbg.setParamCode("xtxxcs");
        jdfbg.setField("jdjgfbbg");
        List<SysParamFieldValueDto> jdfbgList = sysParamValueService.findSysParamFieldAndValueListByCode(jdfbg);
        if (!jdfbgList.isEmpty()) {
            if (jdfbgList.get(0).getValue().equals("1")) {
                if (ToolsUtils.isNotEmpty(bacPublisSecReports.get(0).getStrainNo()) && testNodeNo.equals("PEIYANG")) {
                    List<LabRptmain> labRptmains = new ArrayList<>();
                    // 1.判断系统参数-是否观察发布报告 是的情况下
                    PubReport pubReport = getPubReport(bacPublisSecReports.get(0).getSampleNo(), bacPublisSecReports.get(0).getRptGroup(), bacPublisSecReports.get(0).getSampleda());
                    if (Objects.isNull(pubReport)) {
                        return Result.fail("未找到对应的报告模板");
                    }
                    // 2.删除LAB_RPTMAIN的id(BacPublisSecReport的id),先查询出来结果联合主键和节点 stream 取ids
                    List<String> idS = reports.stream().map(BacPublisSecReport::getId).collect(Collectors.toList());
                    labRptmainService.removeByIds(idS);
                    // 3.遍历bacPublisSecReports,新增LAB_RPTMAIN,id(BacPublisSecReport的id),RPT_TEMPLATE_CODE,动态的模板id
                    List<String> pubIds = bacPublisSecReports.stream().map(BacPublisSecReport::getId).collect(Collectors.toList());
                    for (String pubId : pubIds) {
                        LabRptmain labRptmain = new LabRptmain();
                        labRptmain.setId(pubId);
                        labRptmain.setMainInfoId(pubId);
                        labRptmain.setRptTemplateCode(pubReport.getId());
                        labRptmain.setIsExported(0);
                        labRptmain.setIsFinalReport(1);
                        labRptmain.setSampleda(bacPublisSecReports.get(0).getSampleda());
                        labRptmain.setSampleNo(bacPublisSecReports.get(0).getSampleNo());
                        labRptmain.setRptGroup(bacPublisSecReports.get(0).getRptGroup());
                        labRptmains.add(labRptmain);
                    }
                    labRptmainService.saveBatch(labRptmains);

                    // 修改观察结果
                    LambdaUpdateWrapper<BacObserResult> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
                    lambdaUpdateWrapper.eq(BacObserResult::getDelFlag, 0)
                            .eq(BacObserResult::getRptGroup, bacPublisSecReports.get(0).getRptGroup())
                            .eq(BacObserResult::getSampleNo, bacPublisSecReports.get(0).getSampleNo())
                            .eq(BacObserResult::getSampleda, bacPublisSecReports.get(0).getSampleda())
                            .eq(BacObserResult::getIsolateNum, bacPublisSecReports.get(0).getStrainNo())
                            .set(BacObserResult::getBacPublishStatus, 1);
                    bacObserResultService.update(lambdaUpdateWrapper);
                }
            }
        }
        if (b) {
            for (BacPublisSecReport bacPublisSecReport : bacPublisSecReports) {
                BacStainingResult bacStainingResult = new BacStainingResult();
                bacStainingResult.setIsPushSecReport(1);
                bacStainingResult.setId(bacPublisSecReport.getStainingResulId());
                //根据条件更新报告上传标记
                // LambdaQueryWrapper<BacStainingResult> wrapper = new LambdaQueryWrapper<>();
                // wrapper.eq(BacStainingResult::getDelFlag,0)
                //         .eq(BacStainingResult::getRptGroup,bacPublisSecReport.getRptGroup())
                //         .eq(BacStainingResult::getSampleNo,bacPublisSecReport.getSampleNo())
                //         .eq(BacStainingResult::getTestFlowNo,bacPublisSecReport.getTestFlowNo())
                //         .eq(BacStainingResult::getSampleda,bacPublisSecReport.getSampleda())
                //         .eq(BacStainingResult::getTestNodeNo,bacPublisSecReport.getTestNodeNo())
                //         .eq(BacStainingResult::getStrainNo,bacPublisSecReport.getStrainNo());
                //
                // bacStainingResultMapper.update(bacStainingResult,wrapper);
                bacStainingResultMapper.updateById(bacStainingResult);
            }
            //调用发布微生物二级报告接口
            BacGenerateReportRequestParam bacGenerateReportRequestParam = new BacGenerateReportRequestParam();
            bacGenerateReportRequestParam.setRptGroup(bacPublisSecReports.get(0).getRptGroup());
            bacGenerateReportRequestParam.setSampleda(bacPublisSecReports.get(0).getSampleda());
            bacGenerateReportRequestParam.setSampleNo(bacPublisSecReports.get(0).getSampleNo());
            bacGenerateReportRequestParam.setTestFlowNo(bacPublisSecReports.get(0).getTestFlowNo());
            bacGenerateReportRequestParam.setTestNodeNo(bacPublisSecReports.get(0).getTestNodeNo());
            Result result = labRptmainService.BacGenerateSecondReport(bacGenerateReportRequestParam);

            LambdaQueryWrapper<LabMaininfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper
                    .eq(LabMaininfo::getRptGroup, bacPublisSecReports.get(0).getRptGroup())
                    .eq(LabMaininfo::getSampleNo, bacPublisSecReports.get(0).getSampleNo())
                    .eq(LabMaininfo::getSampleda, bacPublisSecReports.get(0).getSampleda())
                    .eq(LabMaininfo::getDelFlag, 0);

            LabMaininfo labMaininfo = labMaininfoMapper.selectOne(lambdaQueryWrapper);
            if (ToolsUtils.isNotEmpty(bacPublisSecReports)) {
                labMaininfo.setBacFlowNode(bacPublisSecReports.get(0).getTestNodeNo());
            }
            labMaininfoMapper.updateById(labMaininfo);
            JSONObject jsonObject = new JSONObject();
            jsonObject.set("mainInfoId", labMaininfo.getId());
            jsonObject.set("orgId", labMaininfo.getOrgId());
            JSONArray jsonArray = JSONUtil.parseArray(result.getData());
            jsonObject.set("reportList", jsonArray);
            List<String> collect1 = bacPublisSecReports.stream().map(BacPublisSecReport::getStainingResulId).collect(Collectors.toList());
            jsonObject.set("resultIds", collect1);
            LambdaQueryWrapper<SysInterface> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SysInterface::getDelFlag, 0);
            wrapper.eq(SysInterface::getIsEnable, 1);
            wrapper.eq(SysInterface::getOrgId, bacPublisSecReports.get(0).getOrgId());
            List<SysInterface> sysInterfaces = sysInterfaceMapper.selectList(wrapper);
            List<String> collect = sysInterfaces.stream().filter(o -> Objects.nonNull(o) && StringUtils.isNotBlank(o.getInterfaceUrl())).map(SysInterface::getInterfaceUrl).distinct().collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(collect)) {
                for (String webUrl : collect) {
                    String url = webUrl + "/public/releaseWswJjReport";
                    HttpUtil.createPost(url).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(jsonObject)).contentType("application/json").execute().body();
                    /*微生物发送一级二级报告回传his*/
                    SysParamParam sysp1 = new SysParamParam();
                    sysp1.setParamCode("xtxxcs");
                    sysp1.setField("wswfsyjejbghchis");
                    List<SysParamFieldValueDto> r1 = sysParamValueService.findSysParamFieldAndValueListByCode(sysp1);
                    if (!r1.isEmpty()) {
                        if (r1.get(0).getValue().equals("1")) {
                            //染色节点调用二级接口发布报告
                            if ("STAINING".equals(bacPublisSecReports.get(0).getTestNodeNo())) {
                                SysUser sysUser = RedisUserManager.getUser();
                                String releaseReport = webUrl + "/public/releaseWswReport";
                                List<Map> list = new ArrayList<>();
                                Map<String, Object> releaseReportMap = new HashMap<>();
                                HashMap<Object, Object> map1 = new HashMap<>();
                                map1.put("rptGroup", labMaininfo.getRptGroup());
                                map1.put("sampleNo", labMaininfo.getSampleNo());
                                map1.put("sampleda", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(labMaininfo.getSampleda()));
                                list.add(map1);
                                releaseReportMap.put("orgId", sysUser.getOrgId());
                                //子报告
                                releaseReportMap.put("children", "1");
                                releaseReportMap.put("reportInfos", list);
                                releaseReportMap.put("username", sysUser.getUsername());
                                releaseReportMap.put("realname", sysUser.getRealname());
                                String release = HttpUtil.createPost(releaseReport).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(releaseReportMap)).contentType("application/json").execute().body();
                                logger.info("微生物发布二级报告返回值:\n" + release);
                            }
                        }
                    }
                }
            }
        }
        return Result.succ(1, "成功", "");
    }

    @Override
    public Result batchEditRevokeSecReport(BacPublisSecReport bacPublisSecReports) {

        LambdaUpdateWrapper<BacObserResult> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        lambdaUpdateWrapper.eq(BacObserResult::getDelFlag, 0)
                .eq(BacObserResult::getRptGroup, bacPublisSecReports.getRptGroup())
                .eq(BacObserResult::getSampleNo, bacPublisSecReports.getSampleNo())
                .eq(BacObserResult::getSampleda, bacPublisSecReports.getSampleda())
                .eq(BacObserResult::getIsolateNum, bacPublisSecReports.getStrainNo())
                .set(BacObserResult::getBacPublishStatus, 0);
        bacObserResultService.update(lambdaUpdateWrapper);
        LambdaQueryWrapper<LabMaininfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(LabMaininfo::getRptGroup, bacPublisSecReports.getRptGroup())
                .eq(LabMaininfo::getSampleda, bacPublisSecReports.getSampleda())
                .eq(LabMaininfo::getSampleNo, bacPublisSecReports.getSampleNo())
                .eq(LabMaininfo::getDelFlag, 0);
        LabMaininfo labMaininfo = labMaininfoMapper.selectOne(lambdaQueryWrapper);
        //调用发送微生物报告接口
        SysUser sysUser = RedisUserManager.getUser();
        LambdaQueryWrapper<SysInterface> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysInterface::getDelFlag, 0);
        wrapper.eq(SysInterface::getIsEnable, 1);
        wrapper.eq(SysInterface::getOrgId, sysUser.getOrgId());
        List<SysInterface> sysInterfaces = sysInterfaceMapper.selectList(wrapper);
        List<String> collect = sysInterfaces.stream().filter(o -> Objects.nonNull(o) && StringUtils.isNotBlank(o.getInterfaceUrl())).map(SysInterface::getInterfaceUrl).distinct().collect(Collectors.toList());
        //标本消申
        if (com.baomidou.mybatisplus.core.toolkit.CollectionUtils.isNotEmpty(collect)) {
            for (String webUrl : collect) {
                //消审走报告发布传delete
                Map releaseReportMap1 = new HashMap();
                String releaseReport1 = webUrl + "/public/releaseWswReport";
                releaseReportMap1.put("orgId", labMaininfo.getOrgId());
                releaseReportMap1.put("mainInfoId", labMaininfo.getId());
                releaseReportMap1.put("deleteFlag", "1");
                String release = HttpUtil.createPost(releaseReport1).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(releaseReportMap1)).contentType("application/json").execute().body();
                logger.info("消申报告报告返回值:\n" + release);
            }
        }
        return Result.succ(1, "成功", "");
    }

    @Override
    public Result getBacPublisSecReports(BacPublisSecReport bacPublisSecReport) {
        LambdaQueryWrapper<BacPublisSecReport> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(BacPublisSecReport::getDelFlag, 0);
        lambdaQueryWrapper.eq(BacPublisSecReport::getRptGroup, bacPublisSecReport.getRptGroup());
        lambdaQueryWrapper.eq(BacPublisSecReport::getSampleNo, bacPublisSecReport.getSampleNo());
        if (ToolsUtils.isNotEmpty(bacPublisSecReport.getSampleda())) {
            Timestamp timestamp = new Timestamp(bacPublisSecReport.getSampleda().getTime());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String formattedDate = sdf.format(timestamp);
            Timestamp startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
            Timestamp endTime = Timestamp.valueOf(formattedDate + " 23:59:59");
            lambdaQueryWrapper.ge(BacPublisSecReport::getSampleda, startTime);
            lambdaQueryWrapper.le(BacPublisSecReport::getSampleda, endTime);
        }
        lambdaQueryWrapper.eq(ToolsUtils.isNotEmpty(bacPublisSecReport.getTestFlowNo()), BacPublisSecReport::getTestFlowNo, bacPublisSecReport.getTestFlowNo());
        lambdaQueryWrapper.eq(ToolsUtils.isNotEmpty(bacPublisSecReport.getTestNodeNo()), BacPublisSecReport::getTestNodeNo, bacPublisSecReport.getTestNodeNo());
        lambdaQueryWrapper.eq(ToolsUtils.isNotEmpty(bacPublisSecReport.getStrainNo()), BacPublisSecReport::getStrainNo, bacPublisSecReport.getStrainNo());
        if (ToolsUtils.isNotEmpty(bacPublisSecReport.getSearchType()) && bacPublisSecReport.getSearchType().equals(2)) {
            lambdaQueryWrapper.and(p -> p.ne(BacPublisSecReport::getIsCancel, 1).or().isNull(BacPublisSecReport::getIsCancel));
        }
        if (ToolsUtils.isNotEmpty(bacPublisSecReport.getSearchType()) && bacPublisSecReport.getSearchType().equals(3)) {
            lambdaQueryWrapper.eq(BacPublisSecReport::getIsCancel, 1);
        }
        List<BacPublisSecReport> list = bacPublisSecReportMapper.selectList(lambdaQueryWrapper);

        if (ToolsUtils.isNotEmpty(list)) {
            List<String> ids = list.stream().map(BacPublisSecReport::getStainingResulId).collect(Collectors.toList());

            LambdaQueryWrapper<BacStainingResult> bacBloodCultrueQueryMapper = new LambdaQueryWrapper<>();
            bacBloodCultrueQueryMapper.eq(BacStainingResult::getDelFlag, 0);
            bacBloodCultrueQueryMapper.in(BacStainingResult::getId, ids);
            List<BacStainingResult> bacBloodCultrueList = bacStainingResultMapper.selectList(bacBloodCultrueQueryMapper);

            for (BacPublisSecReport bacPublisSecReport1 : list) {
                List<BacStainingResult> collect = bacBloodCultrueList.stream().filter(a -> a.getId().equals(bacPublisSecReport1.getStainingResulId())).collect(Collectors.toList());
                if (ToolsUtils.isNotEmpty(collect)) {
                    BacStainingResult bacBloodCultrue = collect.get(0);
                    bacPublisSecReport1.setStainingResultDto(bacBloodCultrue);
                }
            }
        }
        return Result.succ(1, "成功", list);
    }

    @Override
    public Result cancelPublisSecReport(BacPublisSecReport bacPublisSecReport) {
        if (ToolsUtils.isNotEmpty(bacPublisSecReport)) {
            bacPublisSecReport.setIsCancel(1);
            if (ToolsUtils.isEmpty(bacPublisSecReport.getCancelDate())) {
                bacPublisSecReport.setCancelDate(new Timestamp(System.currentTimeMillis()));
            }
            SysUser sysUser = null;
            if (ToolsUtils.isEmpty(bacPublisSecReport.getCancelDoctor())) {
                try {
                    sysUser = RedisUserManager.getUser();
                    bacPublisSecReport.setCancelDoctor(ToolsUtils.isNotEmpty(sysUser) && ToolsUtils.isNotEmpty(sysUser.getUsername()) ? sysUser.getUsername() : "");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            if (ToolsUtils.isEmpty(bacPublisSecReport.getCancelReason())) {
                bacPublisSecReport.setCancelReason(ToolsUtils.isNotEmpty(sysUser) && ToolsUtils.isNotEmpty(sysUser.getUsername()) ? "由" + sysUser.getRealname() + "取消 " : "");
            }
            int i = bacPublisSecReportMapper.updateById(bacPublisSecReport);
            //调用取消二级报告发布接口
            LambdaQueryWrapper<LabMaininfo> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper
                    .eq(LabMaininfo::getRptGroup, bacPublisSecReport.getRptGroup())
                    .eq(LabMaininfo::getSampleNo, bacPublisSecReport.getSampleNo())
                    .eq(LabMaininfo::getSampleda, bacPublisSecReport.getSampleda())
                    .eq(LabMaininfo::getDelFlag, 0);

            LabMaininfo labMaininfo = labMaininfoMapper.selectOne(lambdaQueryWrapper);
            JSONObject jsonObject = new JSONObject();
            jsonObject.set("mainInfoId", labMaininfo.getId());
            jsonObject.set("orgId", labMaininfo.getOrgId());
            jsonObject.set("resultId", bacPublisSecReport.getStainingResultDto().getId());
            LambdaQueryWrapper<SysInterface> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SysInterface::getDelFlag, 0);
            wrapper.eq(SysInterface::getIsEnable, 1);
            wrapper.eq(SysInterface::getOrgId, bacPublisSecReport.getOrgId());
            List<SysInterface> sysInterfaces = sysInterfaceMapper.selectList(wrapper);
            List<String> collect = sysInterfaces.stream().filter(o -> Objects.nonNull(o) && StringUtils.isNotBlank(o.getInterfaceUrl())).map(SysInterface::getInterfaceUrl).distinct().collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(collect)) {
                for (String webUrl : collect) {
                    String url = webUrl + "/public/cancleWswJjReport";
                    HttpUtil.createPost(url).setConnectionTimeout(3000).body(JSONUtil.toJsonStr(jsonObject)).contentType("application/json").execute().body();
                }
            }
            return Result.succ(1, "成功", bacPublisSecReport);
        }
        return Result.fail("取消失败");
    }

    @Override
    public Result deletePublisSecReport(BacPublisSecReport bacPublisSecReport) {
        if (ToolsUtils.isEmpty(bacPublisSecReport)) {
            return Result.fail("没有要删除的报告");
        }
        if (ToolsUtils.isNotEmpty(bacPublisSecReport.getIsCancel()) && !bacPublisSecReport.getIsCancel().equals(1)) {
            return Result.fail("请先取消发布报告");
        }
        int i = bacPublisSecReportMapper.deleteById(bacPublisSecReport.getId());
        return Result.succ(i > 0 ? 1 : 0, i > 0 ? "删除成功" : "删除失败", bacPublisSecReport);
    }

    public PubReport getPubReport(String sampleNo, String rptGroup, Timestamp sampleda) {
        CommonPageDto pageParam = new CommonPageDto();
        pageParam.setCode("YWBD");
        Result dictResult = basDictDetailService.findDictDetailList(pageParam);
        if (ToolsUtils.isEmpty(dictResult)) {
            return null;
        }
        List<Map<String, Object>> data = (List<Map<String, Object>>) dictResult.getData();

        List<Map<String, Object>> filteredList = data.stream().filter(map -> "1745380128773828610".equals(map.get("moduleId")) && "002".equals(map.get("pointsCode"))).collect(Collectors.toList());
        if (ToolsUtils.isEmpty(filteredList)) {
            return null;
        }

        String pointId = filteredList.get(0).get("commonId").toString();
        Timestamp timestamp = new Timestamp(sampleda.getTime());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String formattedDate = sdf.format(timestamp);
        Timestamp startTime = Timestamp.valueOf(formattedDate + " 00:00:00");
        Timestamp endTime = Timestamp.valueOf(formattedDate + " 23:59:59");

        //查询是否有图片
        LambdaQueryWrapper<BacImageResult> bacImageResultQuery = new LambdaQueryWrapper<>();
        bacImageResultQuery.eq(BacImageResult::getDelFlag, 0);
        bacImageResultQuery.eq(BacImageResult::getSampleNo, sampleNo);
        bacImageResultQuery.eq(BacImageResult::getIsSelected, 1);
        bacImageResultQuery.in(BacImageResult::getRptGroup, rptGroup);
        bacImageResultQuery.ge(BacImageResult::getSampleda, startTime);
        bacImageResultQuery.le(BacImageResult::getSampleda, endTime);
        // bacImageResultQuery.in(BacImageResult::getSampleda, input.getSampleda());

        // 增加菌株匹配选择，若菌株号存在，则匹配
        int imgCount = bacImageResultMapper.selectCount(bacImageResultQuery);
        //计算使用的模板Id,模板名称
        LambdaQueryWrapper<PubReport> pubRptQuery = new LambdaQueryWrapper();
        pubRptQuery.eq(PubReport::getDelFlag, 0);
        pubRptQuery.eq(PubReport::getPointsId, pointId);
        if (imgCount > 0) {
            pubRptQuery.eq(PubReport::getIncludeImages, 1);
        }
        pubRptQuery.eq(PubReport::getIsUse, 1);

        List<PubReport> pubReportList = pubReportMapper.selectList(pubRptQuery);
        if (ToolsUtils.isEmpty(pubReportList)) {
            return null;
        }
        PubReport pubReport = pubReportList.get(0);
        return pubReport;
    }
}
